//
//  GYEmoticonKeyboardView.swift
//  Weibo
//
//  Created by vane on 16/8/18.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class GYEmoticonKeyboardView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        addSubview(emoticonBottomView)
        addSubview(emoticonPageView)
        
        emoticonBottomView.snp_makeConstraints { (make) -> Void in
            
            make.leading.bottom.trailing.equalTo(self)
            make.height.equalTo(37)
        }
        
        emoticonBottomView.closure = {(type: GYEmoticonBottomViewType)->() in
            
            let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)

            self.emoticonPageView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            
            
            }
        
        
        emoticonPageView.snp_makeConstraints { (make) -> Void in
            
            make.leading.top.trailing.equalTo(self)
            make.bottom.equalTo(emoticonBottomView.snp_top)
        }
        
    }
    
    private lazy var emoticonBottomView:GYEmoticonBottomView = GYEmoticonBottomView()
    
    private lazy var emoticonPageView:GYEmoticonPageView = {
        
       let view = GYEmoticonPageView()
        
        view.bounces = false
        view.pagingEnabled = true
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        view.delegate = self

        return view
    }()
}
extension GYEmoticonKeyboardView:UICollectionViewDelegate{
    
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let centerX = SCREENW*0.5 + scrollView.contentOffset.x
        
        let cells = self.emoticonPageView.visibleCells().sort { (cell1, cell2) -> Bool in
            
            return cell1.frame.origin.x < cell2.frame.origin.x
        }
        
        if cells.count == 2{
            
            let firstCell = cells.first!
            
            let lastCell = cells.last!
            
            let indexPath: NSIndexPath
            
            if firstCell.frame.contains(CGPoint(x: centerX, y: 0)){
                
                indexPath = emoticonPageView.indexPathForCell(firstCell)!
                
            }else{
                
                indexPath = emoticonPageView.indexPathForCell(lastCell)!

            }
            
              emoticonBottomView.setupCurrentButton(indexPath.section)
        }
        
    }
    
    
    
}